
'use client'
import { heatAdd, heatList, heatUpdate } from "@/actions/action_heat";
import { FieldType, addData, getDataList, } from "@/actions/listDeal";
import LineEchart from "@/components/line_echart";
import { cn } from "@/utils";
import { RotateRightOutlined, SearchOutlined } from '@ant-design/icons';
import { Space, DatePicker, Button, Form, Modal, InputNumber, Radio, Table, message } from 'antd'
const { RangePicker } = DatePicker;
import type { DatePickerProps } from 'antd';
import { time } from "console";
import dayjs, { Dayjs } from "dayjs";
import isBetween from 'dayjs/plugin/isBetween'	// 引入相关插件
import { Metadata } from "next";
import { useEffect, useMemo, useRef, useState } from "react";
import { tableColumns } from "./dict";
import { useRouter } from "next/navigation";
import dynamic from "next/dynamic";

dayjs.extend(isBetween)

// export const metadata: Metadata = {
//   title: '日常体温记录'
// }
export default function Home() {
  const defaultTimeRange = [dayjs('2024-06-11'), dayjs()]
  const [list, setList] = useState<FieldType[]>([])
  const [formTop] = Form.useForm();
  const [isRotated, setIsRotated] = useState(false)
  const [isEdit, setIsEdit] = useState(false)
  const timeList = async (start: Dayjs, end: Dayjs) => {
    // const source = getDataList()
    const result = await heatList(start.format('YYYY-MM-DD'), end.format('YYYY-MM-DD'))
    const filterLIst = result.map(it => {
      // const ti = it.time.split('-')
      // it.time = `${ti[1]}-${ti[2]}`
      return {
        ...it
      }
    })
    setList(filterLIst)
  }
  let rowId = useRef<number | undefined>();

  const initData: FieldType = { num: 36.6, time: dayjs() as any, isCircle: '0', holiday: '0' }
  const router = useRouter()

  const [visible, setVisible] = useState(false)
  const addRecord = () => {
    rowId.current = undefined
    setVisible(true)
  }

  const disabled7DaysDate: DatePickerProps['disabledDate'] = (current, { from }) => {
    if (from) {
      return Math.abs(current.diff(from, 'days')) >= 30;
    }
    return false;
  };


  // useEffect(() => { // 每次setState都会更新
  //   console.log(31);
  // })

  const [form] = Form.useForm();
  useEffect(() => {
    timeList(defaultTimeRange[0], defaultTimeRange[1])
  }, [])
  return (
    <main className={cn('isRotatedCon','h-[100vh]', {
      'is90': isRotated
    })}>
      <div className="h-20 md:h-14 flex justify-center  items-center">
        <Form
          form={formTop}
          layout='inline'
          initialValues={
            {
              time: defaultTimeRange
            }
          }
          onFinish={(values) => {
            timeList(values.time[0], values.time[1])
          }}>
          <Space>
            <Form.Item
              name="time"
              label="日期范围"
              rules={[{ required: true, message: '日期范围 is required!' }]}
            >
              {/* disabledDate={disabled7DaysDate} */}
              <RangePicker ></RangePicker>
            </Form.Item>
            <Form.Item label="">
              <Space> <Button type="primary" htmlType="submit">
                查询
              </Button>
                <Button onClick={() => {
                  formTop.resetFields()
                  timeList(defaultTimeRange[0], defaultTimeRange[1])
                }} >
                  重置
                </Button>
                <Button onClick={addRecord} type='dashed' danger>
                  新增
                </Button>
                <span className="block md:hidden">
                  <Button onClick={() => {
                    setIsEdit(true)
                  }} type='primary'  >
                    编辑
                  </Button>
                </span>
                <span className="block md:hidden">
                  <Button onClick={() => {
                    const time = formTop.getFieldsValue().time
                    if (!time) {
                      message.error('请选择日期')
                      return
                    }
                    router.push(`/web/canvas?start=${time[0].format('YYYY-MM-DD')}&end=${time[1].format('YYYY-MM-DD')}`)
                  }} type='primary'  >
                    去打印
                  </Button>
                </span>

                <span className='hidden md:inline-block'>
                  <Button type="primary" onClick={() => {
                    setIsRotated(!isRotated)
                  }} icon={<RotateRightOutlined />} />
                </span>

              </Space>

            </Form.Item>
          </Space>
        </Form>
      </div>
      <div className="w-full flex-1">
        <LineEchart isRotaded={isRotated} list={list}></LineEchart>
      </div>

      {/* 查看列表  */}
      <Modal open={isEdit} centered title="温度列表" footer={null} width='80%' onCancel={() => setIsEdit(false)}>
        <Table
          scroll={{ y: '60vh' }}
          columns={[...tableColumns, {
            title: '操作',
            dataIndex: 'operation',
            render: (_, record) => (
              <Button size="small" type='dashed' onClick={() => {

                setVisible(true)
                // console.log(form);
                // console.log(form.getFieldsValue(true));

                rowId.current = record.id
                form.setFieldsValue({
                  ...record,
                  time: dayjs(record.time)
                })
              }}>编辑</Button>
            )
          }]} dataSource={list.map(it => {
            return {
              ...it,
              key: it.id,
            }
          })} />
      </Modal>
      {/* form表单 */}
      <Modal
        open={visible}
        title="添加温度"
        zIndex={1004}
        okButtonProps={{ autoFocus: true, htmlType: 'submit' }}
        onCancel={() => {
          rowId.current = undefined;
          setVisible(false)
        }}
        modalRender={(dom) => (
          <Form
            layout='horizontal'
            form={form}
            name="form_in_modal"
            initialValues={initData}
            clearOnDestroy
            onFinish={async (values) => {
              Modal.confirm({
                title: "提示",
                content: "您确定要提交吗？",
                onOk: async () => {
                  const params = {
                    ...values,
                    time: values.time.format('YYYY-MM-DD')
                  }
                  let flag: any = false

                  if (rowId.current) {
                    flag = await heatUpdate(rowId.current as number, params)
                  } else {
                    flag = await heatAdd(params)
                  }

                  if (flag === true) {
                    setVisible(false)
                    const temp = formTop.getFieldsValue().time
                    timeList(temp[0], temp[1])
                  } else {
                    message.error(flag)
                  }
                  // if (!flag) {
                  //   message.error('该日期数据已经存在，请勿重复添加')
                  //   return
                  // }

                  // console.log();
                }
              });

            }}
          >
            {dom}
          </Form>
        )}
      >

        <Form.Item<FieldType>
          label="日期"
          name="time"

          rules={[{ required: true, message: '请选择日期' }]}
        >
          <DatePicker disabled={!!rowId.current} style={{ width: '100%' }}></DatePicker>
        </Form.Item>
        <Form.Item<FieldType>
          label="温度"
          name="num"
          rules={[{ required: true, message: 'Please input 温度!' }]}
        >
          <InputNumber style={{ width: '100%' }} />
        </Form.Item>
        <Form.Item<FieldType>
          label="圆圈"
          name="isCircle"
          rules={[{ required: true, message: '' }]}
        >
          <Radio.Group>
            <Radio value="1">是</Radio>
            <Radio value="0">否</Radio>
          </Radio.Group>
        </Form.Item>
        <Form.Item<FieldType>
          label="是否例假"
          name="holiday"
          rules={[{ required: true, message: '' }]}
        >
          <Radio.Group>
            <Radio value="1">有</Radio>
            <Radio value="0">无</Radio>
          </Radio.Group>
        </Form.Item>
      </Modal>
    </main>
  );
}
